using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;

namespace Pronghorn.Core
{
	public class MinimizeAndCombineJsController : ProngHornControllerBase
	{
		private readonly IFileLocator _fileLocator;
		private readonly IFileMinifier _fileMinifier;

		public MinimizeAndCombineJsController(ViewDataDictionary<IProngHornSkinContext> viewDataDictionary,
		                                      ISiteContext siteContext, IIocContainer container)
			: base(viewDataDictionary, siteContext, container)
		{
			_fileMinifier = Container.Resolve<IFileMinifier>();
			_fileLocator = Container.Resolve<IFileLocator>("jsFileLocator");
		}

		private IEnumerable<JavaScriptTag> getListOfScripts(IEnumerable<string> fileIds)
		{
			foreach (string fileId in fileIds)
			{
				string[] fileIdParts = fileId.Split('-');
				var fileContext = Container.Resolve<IFileConventions>(fileIdParts[0]);
				string filePath = _fileLocator.GetFileLocation(fileIdParts[1], fileContext);
				yield return new JavaScriptTag(new Uri(filePath, UriKind.RelativeOrAbsolute));
			}
		}

		protected string Render(IEnumerable<JavaScriptTag> scripts)
		{
			var writer = new StringWriter();
			foreach (JavaScriptTag javaScriptTag in scripts)
			{
				var code = javaScriptTag.Code;
				_fileMinifier.Minify(code, writer);
			}
			return writer.ToString();
		}

		public JavaScriptResult Index(string files)
		{
			var result = new JavaScriptResult {Script = string.Empty};
			if (files == null)
			{
				files = Request.QueryString["files"];
			}
			if (string.IsNullOrEmpty(files))
			{
				return result;
			}
			result.Script = Render(getListOfScripts(splitArguments(files)));
			return result;
		}

		private static IEnumerable<string> splitArguments(string files)
		{
			if (files.IndexOf(',') > -1)
			{
				return files.Split(',');
			}
			return files.Split('|');
		}
	}
}